'use strict';

const Service = require('egg').Service;
const utils = require('../extend/dun-utils');
const { commonErr, success } = require('../extend/helper');

class IdentityService extends Service {

    /**
     * 学历认证
     */
    async education(user_id, data) {
        const user = await this.ctx.model.User.findByPk(user_id);
        if (!user) {
            commonErr("用户不存在");
        }
        if (user.education == 2) {
            commonErr("您已经学历验证了，无需再次验证");
        }
        const certificate = await this.ctx.model.UserCertificate.findOne({
            where: {
                user_id
            }
        })
        if (!certificate) {
            data.user_id = user_id;
            await this.ctx.model.UserCertificate.create(data);
        } else {
            await this.ctx.model.UserCertificate.update(data, {
                where: {
                    id: certificate.id
                }
            })
        }
    }

    /**
     * 实名验证
     */
    async checkIdCard(user_id, username, card_no) {
        const user = await this.ctx.model.User.findByPk(user_id);
        if (!user) {
            commonErr("用户不存在");
        }
        if (user.identity == 2) {
            commonErr("您已经实名验证了，无需再次验证");
        }
        //产品密钥ID，产品标识
        var secretId = "8bc13ac20636a463b6c7b749f6ea2d8f";
        // 产品私有密钥，服务端生成签名信息使用，请严格保管，避免泄露
        var secretKey = "46f6cebcc041fcbcb11917611aae03da";
        // 业务ID，易盾根据产品业务特点分配
        var businessId = "17c6ba7780f1463982ff812d751d5f69";
        // 易盾身份认证服务身份证实名认证在线检测接口地址
        var apiurl = "https://verify.dun.163.com/v1/idcard/check";
        //请求参数
        var post_data = {
            // 1.设置公有有参数
            secretId: secretId,
            businessId: businessId,
            version: "v1",
            timestamp: new Date().getTime(),
            nonce: utils.noncer(),
            // 2.设置私有参数
            name: username,
            cardNo: card_no,
        };
        var signature = utils.genSignature(secretKey, post_data);
        post_data.signature = signature;
        const responseData = await utils.sendHttpRequest(apiurl, "POST", post_data);
        var data = JSON.parse(responseData);
        if (data.code == 200) {
            //认证不通过
            if (data.result.status != 1 && data.result.reasonType != 1) {
                if (data.result.reasonType == 2) {
                    commonErr('输入姓名和身份证号不一致');
                }
                if (data.result.reasonType == 3) {
                    commonErr('查无此身份证');
                }
            }
            //认证通过
            const transaction = await this.ctx.model.transaction();
            try {
                //更新认证
                const certificate = await this.ctx.model.UserCertificate.findOne({
                    where: {
                        user_id
                    }
                })
                if (!certificate) {
                    this.ctx.model.UserCertificate.create({
                        user_id,
                        username,
                        identity_number: card_no,
                        task_id: data.result.taskId
                    })
                } else {
                    certificate.username = username;
                    certificate.identity_number = card_no;
                    certificate.task_id = data.result.taskId;
                    certificate.save();
                }
                //更新用户身份
                user.identity = 2;
                user.save();

                await transaction.commit();
            } catch (error) {
                console.log('ERROR: ' + error)
                await transaction.rollback();
            }
            success();
        } else {
            console.log('Request failed!,msg=' + data.msg);
            commonErr(data.msg);
        }
    }
}

module.exports = IdentityService;